<!-- templates/profile.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人资料 - 贵州省先进计算全省重点实验室</title>
    {% load static %}
    <style>
        /* 这里包含之前的所有CSS样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
            min-height: 100vh;
            color: #2d3748;
        }

        .header {
            background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
            padding: 15px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            border-bottom: 1px solid rgba(74, 85, 104, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            font-size: 40px;
            color: #2d3748;
            margin-left: 10px;
        }

        .back-button {
            padding: 10px 20px;
            background: #4299e1;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .back-button:hover {
            background: #3182ce;
            transform: translateY(-2px);
        }

        .container {
            max-width: 800px;
            margin: 40px auto;
            padding: 0 20px;
        }

        .profile-card {
            background: white;
            border-radius: 16px;
            padding: 40px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
        }

        /* 新增的CSS样式 */
        .region-selector {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .region-select {
            flex: 1;
            min-width: 120px;
        }

        @media (max-width: 768px) {
            .region-selector {
                flex-direction: column;
            }

            .region-select {
                flex: none;
                width: 100%;
            }
        }

        .profile-header {
            text-align: center;
            margin-bottom: 40px;
            padding-bottom: 30px;
            border-bottom: 2px solid #e2e8f0;
        }

        .profile-avatar {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 48px;
            color: white;
            margin: 0 auto 20px;
            cursor: pointer;
            transition: transform 0.3s ease;
        }

        .profile-avatar:hover {
            transform: scale(1.05);
        }

        .profile-title {
            font-size: 28px;
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 10px;
        }

        .profile-subtitle {
            color: #718096;
            font-size: 16px;
        }

        .form-section {
            margin-bottom: 40px;
        }

        .section-title {
            font-size: 20px;
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #e2e8f0;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .form-group {
            margin-bottom: 25px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #4a5568;
            font-size: 14px;
        }

        .form-input {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            font-size: 16px;
            transition: all 0.3s ease;
            background: #f7fafc;
        }

        .form-input:focus {
            outline: none;
            border-color: #4299e1;
            background: white;
            box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.1);
        }

        .phone-group {
            display: flex;
            gap: 10px;
            align-items: end;
        }

        .phone-input {
            flex: 1;
        }

        .verify-button {
            padding: 12px 20px;
            background: #48bb78;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
            white-space: nowrap;
        }

        .verify-button:hover {
            background: #38a169;
        }

        .verify-button:disabled {
            background: #a0aec0;
            cursor: not-allowed;
        }

        .code-group {
            display: flex;
            gap: 10px;
            align-items: end;
            margin-top: 15px;
        }

        .code-input {
            flex: 1;
        }

        .primary-button {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 14px 28px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
        }

        .primary-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3);
        }

        .success-message {
            background: #f0fff4;
            border: 1px solid #9ae6b4;
            color: #22543d;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
        }

        .error-message {
            background: #fed7d7;
            border: 1px solid #feb2b2;
            color: #742a2a;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
        }

        .info-text {
            font-size: 14px;
            color: #718096;
            margin-top: 8px;
        }

        .grid-2 {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        @media (max-width: 768px) {
            .grid-2 {
                grid-template-columns: 1fr;
            }

            .phone-group, .code-group {
                flex-direction: column;
                align-items: stretch;
            }

            .verify-button {
                margin-top: 10px;
            }

            .header h1 {
                font-size: 28px;
            }

            .profile-card {
                padding: 20px;
                margin: 20px 10px;
            }
        }

        .countdown {
            color: #e53e3e;
            font-weight: 600;
        }
    </style>
</head>
<body>
<div class="header">
    <h1>贵州省先进计算全省重点实验室</h1>
    <button class="back-button" onclick="window.location.href='/index/'">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
            <path d="M19 12H5M12 19L5 12L12 5" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                  stroke-linejoin="round"/>
        </svg>
        返回首页
    </button>
</div>

<div class="container">
    <div class="profile-card">
{#        <div class="profile-header">#}
{#            <div class="profile-avatar" onclick="uploadAvatar()" id="profileAvatar">#}
{#                {% if user.avatar %}#}
{#                    <img src="{{ user.avatar.url }}" alt="头像"#}
{#                         style="width: 100%; height: 100%; border-radius: 50%; object-fit: cover;">#}
{#                {% else %}#}
{#                    👤#}
{#                {% endif %}#}
{#            </div>#}
{#            <div class="profile-title">个人资料设置</div>#}
{#            <div class="profile-subtitle">管理您的个人信息和账户安全</div>#}
{#        </div>#}

        <!-- 基本信息 -->
        <div class="form-section">
            <div class="section-title">
                <span>👤</span>
                基本信息
            </div>

            <div class="form-group">
                <label class="form-label">姓名</label>
                <input type="text" class="form-input" id="userName" placeholder="请输入您的姓名"
                       value="{{ profile.real_name|default:'' }}">
            </div>

            <div class="form-group">
                <label class="form-label">所在地区</label>
                <div class="region-selector">
                    <select class="form-input region-select" id="provinceSelect" onchange="loadCities()">
                        <option value="">请选择省份</option>
                    </select>
                    <select class="form-input region-select" id="citySelect" onchange="loadDistricts()">
                        <option value="">请选择城市</option>
                    </select>
                    <select class="form-input region-select" id="districtSelect">
                        <option value="">请选择区/县</option>
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label class="form-label">学校/机构</label>
                <input type="text" class="form-input" id="userSchool" placeholder="请输入您的学校或工作机构名称"
                       value="{{ profile.school|default:'' }}">
            </div>

            <button class="primary-button" onclick="updateBasicInfo()">更新基本信息</button>
        </div>

{#        <!-- 手机号码 -->#}
{#        <div class="form-section">#}
{#            <div class="section-title">#}
{#                <span>📱</span>#}
{#                手机号码#}
{#            </div>#}
{##}
{#            <div class="success-message" id="phoneSuccessMsg">手机号码更新成功！</div>#}
{#            <div class="error-message" id="phoneErrorMsg">验证码错误，请重新输入</div>#}
{##}
{#            <div class="form-group">#}
{#                <label class="form-label">当前手机号</label>#}
{#                <input type="text" class="form-input" value="{{ profile.get_phone_display }}" readonly#}
{#                       style="background: #f1f5f9; color: #64748b;">#}
{#            </div>#}
{##}
{#            <div class="form-group">#}
{#                <label class="form-label">新手机号</label>#}
{#                <div class="phone-group">#}
{#                    <input type="tel" class="form-input phone-input" id="newPhone" placeholder="请输入新手机号">#}
{#                    <button class="verify-button" id="sendCodeBtn" onclick="sendVerificationCode()">发送验证码</button>#}
{#                </div>#}
{#            </div>#}
{##}
{#            <div class="form-group">#}
{#                <label class="form-label">验证码</label>#}
{#                <div class="code-group">#}
{#                    <input type="text" class="form-input code-input" id="verificationCode"#}
{#                           placeholder="请输入6位验证码">#}
{#                </div>#}
{#                <div class="info-text">验证码将发送到您的新手机号码</div>#}
{#            </div>#}
{##}
{#            <button class="primary-button" onclick="updatePhone()">更新手机号码</button>#}
{#        </div>#}

        <!-- 密码修改 -->
        <div class="form-section">
            <div class="section-title">
                <span>🔒</span>
                密码修改
            </div>

            <div class="success-message" id="passwordSuccessMsg">密码修改成功！</div>
            <div class="error-message" id="passwordErrorMsg">当前密码错误</div>

            <div class="form-group">
                <label class="form-label">当前密码</label>
                <input type="password" class="form-input" id="currentPassword" placeholder="请输入当前密码">
            </div>

            <div class="form-group">
                <label class="form-label">新密码</label>
                <input type="password" class="form-input" id="newPassword" placeholder="请输入新密码">
                <div class="info-text">密码长度至少8位，包含字母和数字</div>
            </div>

            <div class="form-group">
                <label class="form-label">确认新密码</label>
                <input type="password" class="form-input" id="confirmPassword" placeholder="请再次输入新密码">
            </div>

            <button class="primary-button" onclick="updatePassword()">修改密码</button>
        </div>
    </div>
</div>
{% load static %}
<script src="{% static 'js/crypto-js.min.js' %}"></script>

<script>
    // 获取CSRF Token
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    const csrftoken = getCookie('csrftoken');

    // 通用的Ajax请求函数
    function makeRequest(url, data, successCallback, errorCallback) {
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrftoken,
            },
            body: JSON.stringify(data)
        })
            .then(response => response.json())
            .then(data => {
                console.log(data)
                if (data.success) {
                    alert("更新成功")
                    window.location.assign("/index/");
                } else {
                    errorCallback(data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                errorCallback('网络错误，请稍后重试');
            });
    }

    let countdown = 0;
    let countdownTimer = null;

    // 地区数据（简化版，实际项目中建议从API获取）
    const regionData = {
        "贵州省": {
            "贵阳市": ["南明区", "云岩区", "花溪区", "乌当区", "白云区", "观山湖区", "开阳县", "息烽县", "修文县", "清镇市"],
            "遵义市": ["红花岗区", "汇川区", "播州区", "桐梓县", "绥阳县", "正安县", "道真县", "务川县", "凤冈县", "湄潭县", "余庆县", "习水县", "赤水市", "仁怀市"],
            "六盘水市": ["钟山区", "六枝特区", "水城县", "盘州市"],
            "安顺市": ["西秀区", "平坝区", "普定县", "镇宁县", "关岭县", "紫云县"],
            "毕节市": ["七星关区", "大方县", "黔西县", "金沙县", "织金县", "纳雍县", "威宁县", "赫章县"],
            "铜仁市": ["碧江区", "万山区", "江口县", "玉屏县", "石阡县", "思南县", "印江县", "德江县", "沿河县", "松桃县"],
            "黔西南州": ["兴义市", "兴仁市", "普安县", "晴隆县", "贞丰县", "望谟县", "册亨县", "安龙县"],
            "黔东南州": ["凯里市", "黄平县", "施秉县", "三穗县", "镇远县", "岑巩县", "天柱县", "锦屏县", "剑河县", "台江县", "黎平县", "榕江县", "从江县", "雷山县", "麻江县", "丹寨县"],
            "黔南州": ["都匀市", "福泉市", "荔波县", "贵定县", "瓮安县", "独山县", "平塘县", "罗甸县", "长顺县", "龙里县", "惠水县", "三都县"]
        }
    };

    // 初始化地区选择器
    function initRegionSelector() {
        const provinceSelect = document.getElementById('provinceSelect');

        // 清空并添加省份选项
        provinceSelect.innerHTML = '<option value="">请选择省份</option>';

        for (const province in regionData) {
            const option = document.createElement('option');
            option.value = province;
            option.textContent = province;
            provinceSelect.appendChild(option);
        }

        // 如果有已保存的地区信息，则设置默认值
        const savedRegion = "{{ profile.region|default:'' }}";
        if (savedRegion) {
            parseAndSetRegion(savedRegion);
        }
    }

    // 加载城市列表
    function loadCities() {
        const provinceSelect = document.getElementById('provinceSelect');
        const citySelect = document.getElementById('citySelect');
        const districtSelect = document.getElementById('districtSelect');

        const selectedProvince = provinceSelect.value;

        // 清空城市和区县选择器
        citySelect.innerHTML = '<option value="">请选择城市</option>';
        districtSelect.innerHTML = '<option value="">请选择区/县</option>';

        if (selectedProvince && regionData[selectedProvince]) {
            for (const city in regionData[selectedProvince]) {
                const option = document.createElement('option');
                option.value = city;
                option.textContent = city;
                citySelect.appendChild(option);
            }
        }
    }

    // 加载区县列表
    function loadDistricts() {
        const provinceSelect = document.getElementById('provinceSelect');
        const citySelect = document.getElementById('citySelect');
        const districtSelect = document.getElementById('districtSelect');

        const selectedProvince = provinceSelect.value;
        const selectedCity = citySelect.value;

        // 清空区县选择器
        districtSelect.innerHTML = '<option value="">请选择区/县</option>';

        if (selectedProvince && selectedCity && regionData[selectedProvince][selectedCity]) {
            regionData[selectedProvince][selectedCity].forEach(district => {
                const option = document.createElement('option');
                option.value = district;
                option.textContent = district;
                districtSelect.appendChild(option);
            });
        }
    }

    // 发送验证码
    function sendVerificationCode() {
        const phoneInput = document.getElementById('newPhone');
        const sendBtn = document.getElementById('sendCodeBtn');

        if (!phoneInput.value.trim()) {
            alert('请先输入手机号码');
            return;
        }

        if (!/^1[3-9]\d{9}$/.test(phoneInput.value)) {
            alert('请输入正确的手机号码');
            return;
        }

        // 发送验证码请求
        makeRequest('{% url "psychology_profile:发送验证码" %}', {
            phone_number: phoneInput.value
        }, function (data) {
            // 成功回调
            sendBtn.disabled = true;
            countdown = 60;
            updateCountdown();

            countdownTimer = setInterval(() => {
                countdown--;
                if (countdown <= 0) {
                    clearInterval(countdownTimer);
                    sendBtn.disabled = false;
                    sendBtn.textContent = '发送验证码';
                    sendBtn.classList.remove('countdown');
                } else {
                    updateCountdown();
                }
            }, 1000);

            alert(data.message);
            // 开发环境显示验证码
            if (data.dev_code) {
                console.log('开发环境验证码：', data.dev_code);
            }
        }, function (error) {
            alert(error);
        });
    }

    function updateCountdown() {
        const sendBtn = document.getElementById('sendCodeBtn');
        sendBtn.textContent = `${countdown}秒后重发`;
        sendBtn.classList.add('countdown');
    }

    // 更新基本信息
    function updateBasicInfo() {
        const userName = document.getElementById('userName').value;
        const userSchool = document.getElementById('userSchool').value;

        // 获取选中的地区信息
        const province = document.getElementById('provinceSelect').value;
        const city = document.getElementById('citySelect').value;
        const district = document.getElementById('districtSelect').value;

        let userRegion = '';
        if (province) {
            userRegion = province;
            if (city) {
                userRegion += city;
                if (district) {
                    userRegion += district;
                }
            }
        }

        if (!userName.trim()) {
            alert('请输入姓名');
            return;
        }

        if (!province) {
            alert('请选择省份');
            return;
        }

        makeRequest('{% url "psychology_profile:更新信息" %}', {
            real_name: userName,
            region: userRegion,
            school: userSchool
        }, function(data) {
            alert(data.message);
        }, function(error) {
            alert(error);
        });
    }

    // 更新手机号码
    function updatePhone() {
        const newPhone = document.getElementById('newPhone').value;
        const verificationCode = document.getElementById('verificationCode').value;
        const successMsg = document.getElementById('phoneSuccessMsg');
        const errorMsg = document.getElementById('phoneErrorMsg');

        // 隐藏所有消息
        successMsg.style.display = 'none';
        errorMsg.style.display = 'none';

        if (!newPhone.trim()) {
            alert('请输入新手机号');
            return;
        }

        if (!/^1[3-9]\d{9}$/.test(newPhone)) {
            alert('请输入正确的手机号码');
            return;
        }

        if (!verificationCode.trim()) {
            alert('请输入验证码');
            return;
        }

        makeRequest('{% url "psychology_profile:更新电话" %}', {
            new_phone: newPhone,
            verification_code: verificationCode
        }, function (data) {
            successMsg.style.display = 'block';
            successMsg.textContent = data.message;
            // 清空输入框
            document.getElementById('newPhone').value = '';
            document.getElementById('verificationCode').value = '';
            // 更新显示的当前手机号
            document.querySelector('input[readonly]').value = data.data.phone_number;

            setTimeout(() => {
                successMsg.style.display = 'none';
            }, 3000);
        }, function (error) {
            errorMsg.style.display = 'block';
            errorMsg.textContent = error;
            setTimeout(() => {
                errorMsg.style.display = 'none';
            }, 3000);
        });
    }

    // 修改密码
    function updatePassword() {

        const currentPassword = document.getElementById('currentPassword').value;
        const newPassword = document.getElementById('newPassword').value;
        const confirmPassword = document.getElementById('confirmPassword').value;
        const successMsg = document.getElementById('passwordSuccessMsg');
        const errorMsg = document.getElementById('passwordErrorMsg');

        // 隐藏所有消息
        successMsg.style.display = 'none';
        errorMsg.style.display = 'none';

        if (!currentPassword.trim()) {
            alert('请输入当前密码');
            return;
        }

        if (!newPassword.trim()) {
            alert('请输入新密码');
            return;
        }

        if (newPassword.length < 8) {
            alert('新密码长度至少8位');
            return;
        }

        if (!/(?=.*[a-zA-Z])(?=.*\d)/.test(newPassword)) {
            alert('新密码必须包含字母和数字');
            return;
        }

        if (newPassword !== confirmPassword) {
            alert('两次输入的密码不一致');
            return;
        }

        makeRequest('{% url "psychology_profile:修改密码" %}', {
            current_password: currentPassword,
            new_password: newPassword,
            confirm_password: confirmPassword
        }, function (data) {
            successMsg.style.display = 'block';
            successMsg.textContent = data.message;
            // 清空输入框
            document.getElementById('currentPassword').value = '';
            document.getElementById('newPassword').value = '';
            document.getElementById('confirmPassword').value = '';

            setTimeout(() => {
                successMsg.style.display = 'none';
            }, 3000);
        }, function (error) {
            errorMsg.style.display = 'block';
            errorMsg.textContent = error;
            setTimeout(() => {
                errorMsg.style.display = 'none';
            }, 3000);
        });
    }

    // 上传头像
    function uploadAvatar() {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = 'image/*';
        input.onchange = function (e) {
            const file = e.target.files[0];
            if (file) {
                // 验证文件大小（2MB）
                if (file.size > 2 * 1024 * 1024) {
                    alert('头像文件大小不能超过2MB');
                    return;
                }

                // 验证文件类型
                const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
                if (!allowedTypes.includes(file.type)) {
                    alert('仅支持JPG、PNG、GIF格式的图片');
                    return;
                }

                // 使用FormData上传文件
                const formData = new FormData();
                formData.append('avatar', file);

                fetch('{% url "psychology_profile:上传头像" %}', {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': csrftoken,
                    },
                    body: formData
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert(data.message);
                            // 更新头像显示
                            if (data.data.avatar_url) {
                                const avatar = document.getElementById('profileAvatar');
                                avatar.innerHTML = `<img src="${data.data.avatar_url}" alt="头像" style="width: 100%; height: 100%; border-radius: 50%; object-fit: cover;">`;
                            }
                        } else {
                            alert(data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('上传失败，请稍后重试');
                    });
            }
        };
        input.click();
    }

    // 页面加载完成后初始化地区选择器
    document.addEventListener('DOMContentLoaded', function() {
        initRegionSelector();
    });
</script>
</body>
</html>